package com.jinzhi.jzweb.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.google.common.collect.Lists;
import com.jinzhi.jzweb.pojo.ModuleConfig.LotteryManagementDto;
import org.springframework.util.StringUtils;

import java.util.List;

/*
 *  @author : JingChangTian
 *  @date   : 2023/9/28 10:18
 *  @description :
 *
 */
public class CustomerDailyImportListener extends AnalysisEventListener {

    List misCodes = Lists.newArrayList();

    /**
     * 每解析一行，回调该方法
     * @param data
     * @param context
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        String unitName = ((LotteryManagementDto) data).getUnitName();
        if (StringUtils.isEmpty(unitName)) {
            throw new RuntimeException(String.format("第%s行院校名称为空，请检查", context.readRowHolder().getRowIndex()));
        }
        if (misCodes.contains(misCodes)) {
            throw new RuntimeException(String.format("第%s行院校名称已重复，请检查", context.readRowHolder().getRowIndex()));
        } else {
            misCodes.add(unitName);
        }


        String teacher = ((LotteryManagementDto) data).getTeacher();
        if (StringUtils.isEmpty(teacher)) {
            throw new RuntimeException(String.format("第%s行院校领队信息为空，请检查", context.readRowHolder().getRowIndex()));
        }

        String court2 = ((LotteryManagementDto) data).getCourt2();
        if (StringUtils.isEmpty(court2)) {
            throw new RuntimeException(String.format("第%s行赛道信息为空，请检查", context.readRowHolder().getRowIndex()));
        }
        if (misCodes.contains(misCodes)) {
            throw new RuntimeException(String.format("第%s行赛道信息已重复，请检查", context.readRowHolder().getRowIndex() + 1));
        } else {
            misCodes.add(court2);
        }
    }

    /**
     * 出现异常回调
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        // ExcelDataConvertException:当数据转换异常的时候，会抛出该异常，此处可以得知第几行，第几列的数据
        if (exception instanceof ExcelDataConvertException) {
            Integer columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
            Integer rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
            String message = "第" + rowIndex + "行，第" + columnIndex + "列" + "数据格式有误，请核实";
            throw new RuntimeException(message);
        } else if (exception instanceof RuntimeException) {
            throw exception;
        } else {
            super.onException(exception, context);
        }
    }

    /**
     * 解析完全部回调
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        misCodes.clear();
    }
}
